import * as vscode from 'vscode';
import MD5 from './md5';
// import { customAlphabet } from 'nanoid';//生成随机id插件

import * as http from 'http';
import * as querystring from 'querystring';
/**
 * @param words 词组
 * @param to 翻译的语言类型
 */
export function translates(words: string[], to = 'en') {
    return new Promise((resolve, reject) => {
        const appId = vscode.workspace.getConfiguration().get('easy-vuei18n-yp.Baidu App Id') as string;
        const appToken = vscode.workspace.getConfiguration().get('easy-vuei18n-yp.Baidu App Id') as string;

        const keyword = [...new Set(words)].join("\n");//去重
        const salt = (new Date).getTime();
        const from = 'zh';
        const code = '20240117001943545' + keyword + salt + 'e0E1HYPuU_mXo0LDbSBZ'//appToken;
        const sign = MD5(code);

        const params = querystring.stringify({
            q: keyword,
            appid: '20240117001943545',//appId,
            salt,
            from,
            to,
            sign,
        });

        const options = {
            host: 'api.fanyi.baidu.com',
            port: 80,
            path: `/api/trans/vip/translate?${params}`,
            method: 'GET',
        };

        const req = http.request(options, (res) => {
            let data = '';

            res.setEncoding('utf8');
            res.on('data', function (chunk) {
                data += chunk;
            });
            res.on('end', () => {
                let result = JSON.parse(data);

                if (result.error_code) {
                    showError(`翻译出错：${result.error_msg}`);
                    reject();
                }

                // eslint-disable-next-line @typescript-eslint/naming-convention
                const { trans_result } = result;

                result = (trans_result || []).reduce((prev: any, cur: any) => {
                    prev[cur.src] = cur.dst;
                    return prev;
                }, {});
                vscode.window.showInformationMessage(`翻译结!果：${result[words[0]]}`);
                resolve(result[words[0]]);
            });
        });

        req.on('error', error => {
            showError('翻译出错，请稍后重试。');
            console.log(error);
            reject();
        });

        req.end();
    });
}



/**
 * 
 * @param errorText 错误信息
 */
function showError(errorText: string) {
    if (errorText) {
        vscode.window.showErrorMessage(errorText);
    }
}
/**
 * 
 * @returns 随机id
 */
export function getId(): string {
    const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    // return customAlphabet(alphabet, 20)();
}
